import { defineStore } from "pinia";

export const basketStore = defineStore("basket", {
  state: () => ({
    basketItems: [],
  }),
  getters: {
    totalNum() {
      return this.basketItems.reduce((pre, cur) => (pre += cur.count ?? 0), 0);
    },
  },
  actions: {
    addItem(item) {
      let isHasItem = this.basketItems.find((v) => v.product_id === item.product_id);
      if (isHasItem) {
        isHasItem.count += 1;
      } else {
        this.basketItems.push({
          ...item,
          count: 1,
        });
      }
    },
  },
  persist: {
    storage: sessionStorage,
    pick: ["basketItems"],
  },
});
